//
//  XS_ZhengshuSearchVC.swift
//  XueDao
//
//  Created by 韩云智 on 2021/1/7.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources

class XS_ZhengshuSearchVC: XS_BaseVC {
    lazy var models: [XS_queryMyIndustryAllM] = []

    override func upView() {
        let search = QMUITextField(frame: CGRect(x: 0, y: 0, width: .scale*303, height: .scale*32))
        self.navigationItem.titleView = search
        search.placeholder = "请输入搜索内容"
        let leftView = UIView(frame: CGRect(x: 0, y: 0, width: .scale*32, height: .scale*32))
        let searchImgV = UIImageView(image: UIImage(named: "icon_16px_搜索备份"))
        searchImgV.frame = CGRect(x: 8, y: 8, width: 16, height: 16) * .scale
        leftView.addSubview(searchImgV)
        search.leftView = leftView
        search.leftViewMode = .always
        search.placeholderColor = #colorLiteral(red: 0.768627451, green: 0.7764705882, blue: 0.8039215686, alpha: 1)
        search.font = .xsFont(name: .regular, .scale*12)
        search.layer.cornerRadius = .scale*16
        search.layer.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        search.returnKeyType = .search
        
        
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: .scale*104, height: .scale*200)
        flowLayout.minimumLineSpacing = .scale*16
        flowLayout.minimumInteritemSpacing = 0
        flowLayout.sectionInset = UIEdgeInsets(top: .scale*56, left: .scale*16, bottom: .scale*16, right: .scale*16)
        let collection = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
        collection.showsVerticalScrollIndicator = false
        collection.showsHorizontalScrollIndicator = false
        collection.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        view.addSubview(collection)
        collection.snp.makeConstraints {
            $0.edges.equalToSuperview()
        }
        
        collection.register(XS_ZhengshuCell.self, forCellWithReuseIdentifier: "cell")
        let dataSource = RxCollectionViewSectionedReloadDataSource<SectionModel<String, XS_queryMyIndustryAllM>>(configureCell: { ds, cv, ip, it in
            let cell = cv.dequeueReusableCell(withReuseIdentifier: "cell", for: ip) as! XS_ZhengshuCell
            cell.modelPS.onNext(it)
            return cell
        })
        collection.rx.modelSelected(XS_queryMyIndustryAllM.self)
            .asDriver()
            .drive(onNext: { [weak self] item in
                let vc = XS_ZhengshuDetailVC()
                vc.id = item.id
                self?.navigationController?.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        
        let tView = UIView()
        collection.addSubview(tView)
        tView.snp.makeConstraints({
            $0.left.top.width.equalToSuperview()
            $0.height.equalTo(.scale*56)
        })
        
        let tLab = UILabel.xsLabel(size: .scale*18, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "证书")
        tView.addSubview(tLab)
        tLab.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.centerY.equalToSuperview()
        })
        let countLab = UILabel()
        countLab.textAlignment = .right
        tView.addSubview(countLab)
        countLab.snp.makeConstraints({
            $0.right.equalTo(-.scale*16)
            $0.centerY.equalToSuperview()
        })
        
        let items = models.filterDuplicates({ $0.id })
        search.rx.text.orEmpty.asDriver()
            .startWith("")
            .flatMapLatest({ text in
                let models: [XS_queryMyIndustryAllM]
                if text.count > 0 {
                    models = items.filter({ $0.name.contains(text) })
                } else {
                    models = []
                }
                
                let text = NSMutableAttributedString()
                do {
                    let attr = NSMutableAttributedString(string: "共 ")
                    attr.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
                    attr.yy_font = .xsFont(name: .regular, .scale*14)
                    text.append(attr)
                }
                do {
                    let attr = NSMutableAttributedString(string: "\(models.count)")
                    attr.yy_color = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
                    attr.yy_font = .xsFont(name: .medium, .scale*14)
                    text.append(attr)
                }
                do {
                    let attr = NSMutableAttributedString(string: " 个")
                    attr.yy_color = #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1)
                    attr.yy_font = .xsFont(name: .regular, .scale*14)
                    text.append(attr)
                }
                text.yy_alignment = .right
                countLab.attributedText = text
                return Driver.just([SectionModel<String, XS_queryMyIndustryAllM>(model: "", items:models)])
            }).drive(collection.rx.items(dataSource: dataSource))
            .disposed(by: disposeBag)
    }
}

class XS_ZhengshuCell: XS_BaseCCell {
    lazy var modelPS = PublishSubject<XS_queryMyIndustryAllM>()
    
    override func upView() {
        let view = UIView()
        view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.addSubview(view)
        view.snp.makeConstraints({
            $0.edges.equalToSuperview()
        })
        
        let imgV = UIImageView()
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        view.addSubview(imgV)
        imgV.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
            $0.height.equalTo(imgV.snp.width).multipliedBy(132.0/104.0)
        })
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), lines: 2)
        view.addSubview(label1)
        label1.snp.makeConstraints({
            $0.top.equalTo(imgV.snp.bottom).offset(.scale*8)
            $0.left.right.equalToSuperview()
            $0.height.equalTo(.scale*20)
        })
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1))
        view.addSubview(label2)
        label2.snp.makeConstraints({
            $0.top.equalTo(label1.snp.bottom).offset(.scale*4)
            $0.left.right.bottom.equalToSuperview()
            $0.height.equalTo(.scale*16)
        })
        
        
        modelPS.subscribe(onNext: { item in
            label1.text = item.name
            label2.text = "\(item.count) 人参考"
            imgV.sd_setImage(with: URL(string: item.imgUrl))
        }).disposed(by: disposeBag)
    }
}

extension Array {
    func filterDuplicates<E: Equatable>(_ filter: (Element) -> E) -> [Element] {
        var result = [Element]()
        for value in self {
            let key = filter(value)
            if !result.map({filter($0)}).contains(key) {
                result.append(value)
            }
        }
        return result
    }
}
